package com.wuming.caiwu.job;

import com.wm.common.cache.WechartCache;
import com.wm.common.pojo.AccessToken;
import com.wm.common.pojo.JsSign;
import com.wm.common.util.GzhUtil;
import com.wuming.caiwu.core.wx.WeiXinConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class WechartJob {

    @Resource
    private WechartCache wechartCache;


    private static Logger logger = LoggerFactory.getLogger(WechartJob.class);

    @Scheduled(fixedDelay = 7000000)
    public void getWechartAccessToken() {
        for (int i = 1; i < 8; i++) {// 每次获取5次，超过5次不再获取，只能等到下一次
            AccessToken accessToken = GzhUtil.getAccessToken(
                    WeiXinConstant.APPID, WeiXinConstant.APPSECRET);
            logger.info("取得微信accessToken：{}:", accessToken);
            if (null != accessToken) {
                wechartCache.updateAcccessToken(accessToken);
                break;
            } else {
                try {
                    Thread.sleep(70000);// 等待多少秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    @Scheduled(fixedDelay = 7000000)
    public void getWechartJsSign() {
        for (int i = 1; i < 8; i++) {// 每次获取5次，超过5次不再获取，只能等到下一次
            AccessToken accessToken = wechartCache.getAccessToken();
            if (null != accessToken) {
                JsSign jsSign = GzhUtil.getJsSign(accessToken);
                logger.info("取得微信JsSign：{}:", jsSign);
                if (null != jsSign) {
                    wechartCache.updateJsSign(jsSign);
                    break;
                } else {
                    try {
                        Thread.sleep(70000);// 等待多少秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                try {
                    Thread.sleep(8000);//
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
